package cn.edkuir.product.service.impl;

import cn.edkuir.common.constant.ProductConstant;
import cn.edkuir.product.dao.AttrAttrgroupRelationDao;
import cn.edkuir.product.dao.AttrGroupDao;
import cn.edkuir.product.dao.CategoryDao;
import cn.edkuir.product.entity.AttrAttrgroupRelationEntity;
import cn.edkuir.product.entity.AttrGroupEntity;
import cn.edkuir.product.entity.CategoryEntity;
import cn.edkuir.product.service.CategoryService;
import cn.edkuir.product.vo.AttrGroupRelationVo;
import cn.edkuir.product.vo.AttrRespVo;
import cn.edkuir.product.vo.AttrVo;
import cn.edkuir.product.vo.spu.Attr;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.edkuir.common.utils.PageUtils;
import cn.edkuir.common.utils.Query;

import cn.edkuir.product.dao.AttrDao;
import cn.edkuir.product.entity.AttrEntity;
import cn.edkuir.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {
    @Autowired
    private AttrAttrgroupRelationDao attrAttrgroupRelationDao;
    @Autowired
    private AttrGroupDao attrGroupDao;
    @Autowired
    private CategoryDao categoryDao;
    @Autowired
    private CategoryService categoryService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    @Transactional
    public void saveAttr(AttrVo attrVo) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attrVo, attrEntity);
        //保存基本数据
        this.save(attrEntity);

        if(attrVo.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() && attrVo.getAttrGroupId() != null) {
            //是基本属性, 保存关联关系
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            attrAttrgroupRelationEntity.setAttrGroupId(attrVo.getAttrGroupId());
            attrAttrgroupRelationEntity.setAttrId(attrEntity.getAttrId());
            attrAttrgroupRelationDao.insert(attrAttrgroupRelationEntity);
        }
    }

    @Override
    public PageUtils queryAttrPage(Map<String, Object> params, Long catelogId, String type) {
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<AttrEntity>()
                .eq("attr_type", "base".equalsIgnoreCase(type) ?
                        ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() : ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode());

        if(catelogId != 0) {
            wrapper.eq("catelog_id", catelogId);
        }
        String key = (String) params.get("key");
        if(!StringUtils.isEmpty(key)) {
            //attr_id attr_name
            wrapper.and((obj)->{
               obj.eq("attr_id", key).or().like("attr_name", key);
            });
        }

        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                wrapper
        );
        PageUtils pageUtils = new PageUtils(page);
        List<?> list = pageUtils.getList();
        List<AttrRespVo> respVoList = list.stream().map((attrEntity) -> {
            AttrRespVo attrRespVo = new AttrRespVo();
            BeanUtils.copyProperties(attrEntity, attrRespVo);

            //查询分组名字
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = attrAttrgroupRelationDao.selectOne(
                    new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrRespVo.getAttrId())
            );
            if (attrAttrgroupRelationEntity != null) {
                Long groupId = attrAttrgroupRelationEntity.getAttrGroupId();
                if(groupId != null) {
                    AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrAttrgroupRelationEntity.getAttrGroupId());
                    attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }

            //查询分类名字
            CategoryEntity categoryEntity = categoryDao.selectById(attrRespVo.getCatelogId());
            if (categoryEntity != null) {
                attrRespVo.setCatelogName(categoryEntity.getName());
            }

            return attrRespVo;
        }).collect(Collectors.toList());

        pageUtils.setList(respVoList);

        return pageUtils;
    }

    @Override
    public AttrRespVo getAttrInfo(Long attrId) {
        AttrRespVo attrRespVo = new AttrRespVo();
        //查询attr的基本信息
        AttrEntity attrEntity = this.getById(attrId);
        BeanUtils.copyProperties(attrEntity, attrRespVo);

        //是基本属性
        if(attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            //查询分组id和名字
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = attrAttrgroupRelationDao.selectOne(
                    new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrRespVo.getAttrId())
            );
            if(attrAttrgroupRelationEntity != null) {
                Long groupId = attrAttrgroupRelationEntity.getAttrGroupId();
                AttrGroupEntity attrGroupEntity = null;
                if(groupId != null) {
                    attrGroupEntity = attrGroupDao.selectById(groupId);
                }
                attrRespVo.setAttrGroupId(attrAttrgroupRelationEntity.getAttrGroupId());
                if(attrGroupEntity != null) {
                    attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }
        }

        //查询分类完整路径和分类名字
        Long catelogId = attrRespVo.getCatelogId();
        Long[] catelogPath = categoryService.findCatelogPath(catelogId);
        attrRespVo.setCatelogPath(catelogPath);
        CategoryEntity categoryEntity = categoryDao.selectById(catelogId);
        if(categoryEntity != null) {
            attrRespVo.setCatelogName(categoryEntity.getName());
        }

        return attrRespVo;
    }

    @Override
    @Transactional
    public void updateAttr(AttrVo attrVo) {
        //更新基本数据
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attrVo, attrEntity);
        this.updateById(attrEntity);

        //检查关联关系表是否有关联记录
        Integer count = attrAttrgroupRelationDao.selectCount(
                new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getAttrId())
        );

        //是基本属性
        if(attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() && attrVo.getAttrGroupId() != null) {
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            attrAttrgroupRelationEntity.setAttrGroupId(attrVo.getAttrGroupId());
            if(count > 0) {
                //修改分组关联
                attrAttrgroupRelationDao.update(
                        attrAttrgroupRelationEntity,
                        new UpdateWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getAttrId())
                );
            }else {
                //新增关联
                attrAttrgroupRelationEntity.setAttrId(attrVo.getAttrId());
                attrAttrgroupRelationDao.insert(attrAttrgroupRelationEntity);
            }
        }else if(attrVo.getAttrGroupId() == null) {
            //所填写的分组为空, 如果关联关系表有记录则删除
            if(count > 0) {
                attrAttrgroupRelationDao.deleteByAttrId(attrEntity.getAttrId());
            }
        }
    }

    //根据分组id查找关联的所有基本属性
    @Override
    public List<AttrEntity> getRelationAttr(Long attrgroupId) {
        List<AttrAttrgroupRelationEntity> relationEntities = attrAttrgroupRelationDao.selectList(
                new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrgroupId)
        );
        //收集所有属性id
        List<Long> groupIdList = relationEntities.stream().map(AttrAttrgroupRelationEntity::getAttrId).collect(Collectors.toList());

        return groupIdList.size() == 0 ? null : this.listByIds(groupIdList);
    }

    //根据attrId和attrGroupId删除关联关系
    @Override
    public void deleteRelation(List<AttrGroupRelationVo> attrGroupRelationVoList) {
        attrAttrgroupRelationDao.deleteBatchRelation(attrGroupRelationVoList);
    }

    //根据分组id查询当前分组没有关联的所有属性
    @Override
    public PageUtils getNoRelationAttr(Long attrgroupId, Map<String, Object> params) {
        //1.当前分组只能关联自己所属分类下的属性
        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrgroupId);
        Long catelogId = attrGroupEntity.getCatelogId();

        //2.当前分组只能关联没有引用的属性
        //1)找到当前分类下的所有分组
        List<AttrGroupEntity> attrGroupEntityList = attrGroupDao.selectList(
                new QueryWrapper<AttrGroupEntity>().eq("catelog_id", catelogId)
        );
        List<Long> attrGroupIdList = attrGroupEntityList.stream().map(AttrGroupEntity::getAttrGroupId).collect(Collectors.toList());

        //2)这些分组关联的属性
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<AttrEntity>().eq("catelog_id", catelogId)
                .eq("attr_type", ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode());
        if(!CollectionUtils.isEmpty(attrGroupIdList)) {
            List<AttrAttrgroupRelationEntity> relationEntities = attrAttrgroupRelationDao.selectList(
                    new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_group_id", attrGroupIdList)
            );
            List<Long> attrIdList = relationEntities.stream().map(AttrAttrgroupRelationEntity::getAttrId).collect(Collectors.toList());

            //3)从当前分类的所有属性中移除这些属性
            if(!CollectionUtils.isEmpty(attrIdList)) {
                wrapper.notIn("attr_id", attrIdList);
            }
        }

        String key = (String) params.get("key");
        if(!StringUtils.isEmpty(key)) {
            wrapper.and((obj)-> obj.eq("attr_id", key).or().like("attr_name", key));
        }

        //3.移除当前分组已经关联过的属性
//        List<AttrEntity> attrEntityList = this.getRelationAttr(attrgroupId);
//        if(!CollectionUtils.isEmpty(attrEntityList)) {
//            wrapper.notIn("attr_id", attrEntityList.stream().map(AttrEntity::getAttrId).collect(Collectors.toList()));
//        }

        return new PageUtils(this.page(
                new Query<AttrEntity>().getPage(params),
                wrapper
        ));
    }


    //根据attrIdList找到所有可被检索的attr
    @Override
    public List<Long> getSearchableAttrIds(List<Long> attrIds) {
        return this.baseMapper.selectSearchableAttrIds(attrIds);
    }

}